<template>
  <ToolbarButton
    icon="i-ri-chat-3-line"
    title="批注"
    :active="isActive"
    :large-icon="props.largeIcon"
    :hide-text="props.hideText"
    @click="handleClick"
  />
  <CommentDialog
    v-model="dialogVisible"
    :comment-id="currentCommentId"
    :initial-content="currentCommentContent"
    @submit="handleDialogSubmit"
    @close="handleDialogClose"
  />
</template>

<script setup lang="ts">
import { computed, inject, ref, type Ref } from "vue";
import type { Editor } from "@tiptap/vue-3";
import ToolbarButton from "../../../button/index.vue";
import CommentDialog from "../../../comment/CommentDialog.vue";
import { commentActions } from "../../../../store/comment";
import { shortId } from "../../../../utils";
import type { Comment } from "../../../../types/comment";

defineOptions({
  name: "Comment",
});

const props = withDefaults(
  defineProps<{
    largeIcon?: boolean;
    hideText?: boolean;
  }>(),
  {
    largeIcon: false,
    hideText: true,
  }
);

// 注入编辑器实例
const editor = inject<Ref<Editor>>("editor");

const isActive = computed(() => {
  return editor?.value?.isActive("comment");
});

const dialogVisible = ref(false);
const currentCommentId = ref("");
const currentCommentContent = ref("");

const handleClick = () => {
  if (!editor?.value) return;

  const { from, to } = editor.value.state.selection;
  if (from === to) {
    // 如果没有选中文本，提示用户
    alert("请先选中要添加批注的文本");
    return;
  }

  if (editor.value.isActive("comment")) {
    // 如果已有批注，取消批注
    editor.value.commands.unsetComment();
  } else {
    // 添加新批注
    const commentId = `comment-${shortId(8)}`;
    const comment: Comment = {
      id: commentId,
      content: "",
      author: {
        id: "current-user-id", // TODO: 获取当前用户
        name: "当前用户",
        color: "#1890ff",
      },
      createdAt: new Date().toISOString(),
      isResolved: false,
      position: { from, to },
    };

    // 添加批注标记
    editor.value.commands.setComment(commentId, comment.author.id);

    // 保存批注数据
    commentActions.addComment(comment);

    // 设置当前批注ID并打开对话框（先不打开批注面板）
    currentCommentId.value = commentId;
    currentCommentContent.value = "";
    dialogVisible.value = true;
  }
};

const handleDialogSubmit = (content: string) => {
  if (currentCommentId.value) {
    commentActions.updateComment(currentCommentId.value, { content });
    const commentId = currentCommentId.value;
    // 清空当前批注ID（避免在close事件中删除）
    currentCommentId.value = "";
    currentCommentContent.value = "";
    // 提交成功后，打开批注面板并选中该批注
    commentActions.togglePanel();
    commentActions.setActiveComment(commentId);
  }
};

// 处理Dialog关闭事件（用户取消）
const handleDialogClose = () => {
  // 如果用户取消了Dialog，删除已创建的批注标记和数据
  if (currentCommentId.value && editor?.value) {
    const commentId = currentCommentId.value;
    // 从store删除（会同时移除编辑器中的标记）
    commentActions.deleteComment(commentId, editor.value);
  }
  currentCommentId.value = "";
  currentCommentContent.value = "";
};
</script>
